//
//  VideoObj.m
//  demo38vedioToGif
//
//  Created by bing on 16/2/26.
//  Copyright © 2016年 bing. All rights reserved.
//

#import "VideoObj.h"
#import <UIKit/UIKit.h>
#import <AVFoundation/AVTime.h>
#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVAssetImageGenerator.h>
#import <ImageIO/ImageIO.h>
#import <MobileCoreServices/MobileCoreServices.h>

@implementation VideoObj


// 制作GIF图片
- (void)exportAnimatedGifWithImages:(NSArray *)images
{
    // 设置文件路径
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"animated.gif"];
    CGImageDestinationRef destination = CGImageDestinationCreateWithURL((CFURLRef)[NSURL fileURLWithPath:path], kUTTypeGIF, images.count, NULL);
    
    // 播放时间长度
    NSDictionary *frameProperties = [NSDictionary dictionaryWithObject:@{(NSString *)kCGImagePropertyGIFDelayTime:@(images.count * 0.1)}
                                                                forKey:(NSString *)kCGImagePropertyGIFDictionary];
    
    // 循环次数
    NSDictionary *gifProperties = [NSDictionary dictionaryWithObject:@{(NSString *)kCGImagePropertyGIFLoopCount:@(0)}
                                                              forKey:(NSString *)kCGImagePropertyGIFDictionary];
    
    for (UIImage *image in images) {
        CGImageDestinationAddImage(destination, image.CGImage, (CFDictionaryRef)frameProperties);
    }
    
    CGImageDestinationSetProperties(destination, (CFDictionaryRef)gifProperties);
    CGImageDestinationFinalize(destination);
    CFRelease(destination);
    
    NSLog(@"animated GIF file created at %@", path);
    UIImage *savedImage = [UIImage imageWithContentsOfFile:path];
    UIImageWriteToSavedPhotosAlbum(savedImage, nil, nil, nil);
    NSLog(@"ok");
}
@end
